import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import RemoveEffectVarConfirm from '../_base/components/remove-effect-var-confirm'
import useConfig from './use-config'
import type { HtmlExtractorNodeType } from './types'
import cn from '@/utils/classnames'
import VarList from '@/components/workflow/nodes/_base/components/variable/var-list'
import OutputVarList from '@/components/workflow/nodes/_base/components/variable/output-var-list'
import Input from '@/components/workflow/nodes/_base/components/input-support-select-var'
import AddButton from '@/components/base/button/add-button'
import Field from '@/components/workflow/nodes/_base/components/field'
import Split from '@/components/workflow/nodes/_base/components/split'
import { type NodePanelProps } from '@/components/workflow/types'
import BeforeRunForm from '@/components/workflow/nodes/_base/components/before-run-form'
import ResultPanel from '@/components/workflow/run/result-panel'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
import { VarType } from '../../types'
import type { Var } from '../../types'
import { Switch } from 'antd'

const i18nPrefix = 'workflow.nodes.htmlExtractor'

const Panel: FC<NodePanelProps<HtmlExtractorNodeType>> = ({
  id,
  data,
}) => {
  const { t } = useTranslation()

  const [isFocus, setIsFocus] = useState(false)

  const {
    readOnly,
    inputs,
    outputKeyOrders,
    handleSelectorChange,
    handleVarListChange,
    handleAddVariable,
    handleRemoveVariable,
    handleUrlChange,
    handleAttributeChange,
    handleTextChange,
    handleVarsChange,
    handleAddOutputVariable,
    filterVar,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
    // single run
    isShowSingleRun,
    hideSingleRun,
    runningStatus,
    handleRun,
    handleStop,
    runResult,
    inputVarValues,
    setInputVarValues,
  } = useConfig(id, data)

  const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
    onlyLeafNodeVar: false,
    filterVar: (varPayload: Var) => {
      return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
    },
  })

  return (
    <div className='mt-2'>
      <div className='px-4 pt-4 pb-2'>
        <Field
          title={t(`${i18nPrefix}.url`)}
        >
          <Input
            instanceId='html-url'
            className={cn(isFocus ? 'shadow-xs bg-gray-50 border-gray-300' : 'bg-gray-100 border-gray-100', 'grow rounded-lg px-3 py-[6px] border')}
            value={inputs.url}
            onChange={handleUrlChange}
            readOnly={readOnly}
            nodesOutputVars={availableVars}
            availableNodes={availableNodesWithParent}
            onFocusChange={setIsFocus}
            placeholder={!readOnly ? t(`${i18nPrefix}.urlPlaceholder`)! : ''}
            placeholderClassName='!leading-[21px]'
          />
        </Field>
        <Field
          title={t(`${i18nPrefix}.selector`)}
        >
          <Input
            instanceId='html-selector'
            className={cn(isFocus ? 'shadow-xs bg-gray-50 border-gray-300' : 'bg-gray-100 border-gray-100', 'grow rounded-lg px-3 py-[6px] border')}
            value={inputs.selector}
            onChange={handleSelectorChange}
            readOnly={readOnly}
            nodesOutputVars={availableVars}
            availableNodes={availableNodesWithParent}
            onFocusChange={setIsFocus}
            placeholder={!readOnly ? t(`${i18nPrefix}.selectorPlaceholder`)! : ''}
            placeholderClassName='!leading-[21px]'
          />
        </Field>
        <Field
          title={t(`${i18nPrefix}.attribute`)}
        >
          <Input
            instanceId='html-selector'
            className={cn(isFocus ? 'shadow-xs bg-gray-50 border-gray-300' : 'bg-gray-100 border-gray-100', 'grow rounded-lg px-3 py-[6px] border')}
            value={inputs.attribute}
            onChange={handleAttributeChange}
            readOnly={readOnly}
            nodesOutputVars={availableVars}
            availableNodes={availableNodesWithParent}
            onFocusChange={setIsFocus}
            placeholder={!readOnly ? t(`${i18nPrefix}.attributePlaceholder`)! : ''}
            placeholderClassName='!leading-[21px]'
          />
        </Field>
        <Field
          title={t(`${i18nPrefix}.text`)}
        >
          <Switch value={inputs.text} onChange={handleTextChange}></Switch>
        </Field>
      </div>
      <Split />
      <div className='px-4 pt-4 pb-2'>
        <Field
          title={t(`${i18nPrefix}.outputVars`)}
          operations={
            <AddButton onClick={handleAddOutputVariable} />
          }
        >

          <OutputVarList
            readonly={readOnly}
            outputs={inputs.outputs}
            outputKeyOrders={outputKeyOrders}
            onChange={handleVarsChange}
            onRemove={handleRemoveVariable}
          />
        </Field>
      </div>
      {
        isShowSingleRun && (
          <BeforeRunForm
            nodeName={inputs.title}
            onHide={hideSingleRun}
            forms={[
              {
                inputs: [],
                values: inputVarValues,
                onChange: setInputVarValues,
              },
            ]}
            runningStatus={runningStatus}
            onRun={handleRun}
            onStop={handleStop}
            result={<ResultPanel {...runResult} showSteps={false} />}
          />
        )
      }
      <RemoveEffectVarConfirm
        isShow={isShowRemoveVarConfirm}
        onCancel={hideRemoveVarConfirm}
        onConfirm={onRemoveVarConfirm}
      />
    </div >
  )
}

export default React.memo(Panel)
